<template>
    <el-input v-model="searchName" class="w-50 m-2" placeholder="输入名字" :prefix-icon="Search" style="width: 200px" />
    &nbsp;<el-input v-model="searchPrice" class="w-50 m-2" placeholder="输入价格" :prefix-icon="Search" style="width: 200px" />
    &nbsp;<el-input v-model="inventory" class="w-50 m-2" placeholder="库存" :prefix-icon="Search" style="width: 200px" />
    &nbsp; <el-button type="primary" @click="searchBookBywhere()">查询</el-button>
    <br /><br />
    <div style="font-size: 25px">
        <Plus v-if="loginUser.aid == 1" style="width: 1em; height: 1em; margin-right: 8px; color: red"
            @click="addhandler" />
        <!-- Since svg icons do not carry any attributes by default -->
        <!-- You need to provide attributes directly -->
        <!-- <Edit v-if="loginUser.aid == 1" style="width: 1em; height: 1em; margin-right: 8px; color: red"
            @click="Edithandler" /> -->
        <Delete v-if="loginUser.aid == 1" style="width: 1em; height: 1em; margin-right: 8px; color: red"
            @click="handleDelete" />
    </div>

    <el-table :data="booklist" @selection-change="handleSelectionChange" border style="width: 100%">
        <el-table-column type="selection" width="55" />
        <el-table-column label="id" prop="bookId" />

        <el-table-column label="书籍封面" width="180">
            <template #default="scope">
                <div style="display: flex; align-items: center;">
                    <el-image :src="'http://localhost:9000/img/' + scope.row.avatar" v-if="scope.row.avatar" />
                </div>
            </template>
        </el-table-column>


        <el-table-column label="书名" prop="bookName" />
        <el-table-column label="价格" prop="price" sortable />
        <el-table-column label="ISBN" prop="isbn" />


        <el-table-column label="总数" prop="total" />
        <el-table-column label="库存量" prop="plus" />
        <el-table-column align="center" label="操作" width="180">
            <template #default="scope">
                <el-button size="small" type="primary" v-if="loginUser.aid == 2"
                    @click="lendBook(scope.$index, scope.row)">借书
                </el-button>
                <el-button size="small" type="primary" v-if="loginUser.aid == 1"
                    @click="Edithandler(scope.$index, scope.row)">编辑
                </el-button>
                <el-button size="small" type="danger" v-if="loginUser.aid == 1" @click="del(scope.$index, scope.row)">删除
                </el-button>
            </template>
        </el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisible" :title="option" width="30%" draggable>
        <el-form :model="book" label-width="120px">
            <el-form-item label="id" v-if="option == '修改记录'">
                <el-input v-model="book.bookId"  :disabled="option == '修改记录'" />
            </el-form-item>
            <el-form-item label="图书名">
                <el-input v-model="book.bookName" />
            </el-form-item>

            <el-form-item label="价格">
                <el-input v-model.number="book.price" type="number" />
            </el-form-item>

            <el-form-item label="分类">
                <el-select v-model="book.bookType" placeholder="Select">
                    <el-option v-for="item in bookType" :key="item.bookTypeID" :label="item.bookType" :value="item.bookTypeID"
     />
                </el-select>
            </el-form-item>

            <el-form-item label="ISBN">
                <el-input v-model="book.isbn" />
            </el-form-item>
            <el-form-item label="总数">
                <el-input v-model="book.total" />
            </el-form-item>
            <el-form-item label="书籍封面:" label-width="100">
          
                <div style="display: flex; align-items: center; width:150px" v-if="book.avatar">
                    <el-image :src="'http://localhost:9000/img/' + book.avatar" ref="avatarImg" />
                    
                </div>

                <el-upload ref="upload" :limit="1" :on-remove="handleRemove" :on-change="handlerChangeImg"
                    :on-success="uploadSuccess" action="http://localhost:9000/book/uploadFile" :auto-upload="false"
                    list-type="picture-card"><el-icon>
                        <Plus />
                    </el-icon>

                </el-upload>
            </el-form-item>

            <el-form-item>
                <el-button v-if="option == '添加记录'" type="primary" @click="optionBook(option)">添加</el-button>
                <el-button v-if="option == '修改记录'" type="primary" @click="optionBook(option)">修改</el-button>
                <el-button @click="dialogVisible = false">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>

    <el-dialog v-model="dialogLendVisible" title="借书" width="30%" draggable>
        <el-form :model="lendForm" label-width="120px">
            <el-form-item label="书籍信息">
                <el-text>编号：{{ lendForm.bookId }}</el-text>
                &nbsp; &nbsp; &nbsp;
                <el-text>书名：{{ lendForm.bookName }}</el-text>
                &nbsp; &nbsp; &nbsp;
                <el-text>剩余：{{ lendForm.plus }}</el-text>
            </el-form-item>
            <el-form-item label="借书日期">
                <el-col :span="11">
                    <el-date-picker v-model="lendForm.date1" type="date" placeholder="开始日期" style="width: 100%" />
                </el-col>
                <el-col :span="2" class="text-center">
                    <span class="text-gray-500"></span>
                </el-col>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="borrowBook">确定</el-button>
                <el-button>取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
    <div>
        <mypage :total="total" @current="getBooklist" @pageSize="getBooklist" ref="page"></mypage>
    </div>
</template>

<script>
import { ElMessage, ElMessageBox } from "element-plus";
import { Delete, Search, Edit, Plus } from "@element-plus/icons-vue";
import axios from "axios";

import mypage from "../components/page.vue";
import Upload from "../components/upload.vue";

export default {
    //组合api不用加
    components: {
        mypage,
        Upload,
    },

    data() {
        return {
            option: "",
            dialogVisible: false,
            dialogLendVisible: false,
            searchName: "",
            searchPrice: "",
            booklist: [],
            book: {
                bookId: "",
                bookName: "",
                price: 0,
                isbn: "",
                plus: 0,
                total: 0,
                avatar: "",
                bookType: ""
            },
            lendForm: {
                bookId: "",
                uid: "",
                bookName: "",
                price: "",
                plus: "",
                data1: "",
                data2: "",
            },

            total: 0,
            loginUser: {},
            multipleSelection: [],
            fileList: [],

            bookType: {
                bookTypeID: "",
                bookType: ""
            }
        };
    },

    mounted: function () {
        this.loginUser = JSON.parse(sessionStorage.getItem("user"));

        this.getBooklist({
            pageindex: this.$refs.page.currentPage,
            pagesize: this.$refs.page.pageSize,
        });
        this. getBookType();
    },

    methods: {


        getBookType() {
            axios.get("/book/getBookTypes").then(res => {
                if (res.data.code == 200) {
                    this.bookType = res.data.result;
                }
            })
        },

        del()
        {
            axios.get("/book/testException").then(res=>{
                console.log(res)
            })
        },

        handleImgRemove() {
            this.book.avatar = ''
        },
        handleRemove() {
            this.$refs.upload.clearFiles()
        },
        //替换图片
        handlerChangeImg() {
            //把旧图片隐藏注意$el.style.display = 'none'
            this.$refs.avatarImg.$el.style.display = 'none'
        },
        submitUpload() {
            this.$refs.upload.submit();
        },



        handleSelectionChange(rows) {
            //  console.log(rows)
            this.multipleSelection = rows.map((item) => item.bookId);
            console.log(this.multipleSelection);
        },

        //按条件查询
        searchBookBywhere() {
            this.getBooklist();
        },

        uploadSuccess() {

            this.getBooklist();
        },

        getBooklist() {
            // 定义 params 对象

            const where = {
                bookName: this.searchName,
                price: this.searchPrice,
                pageindex: this.$refs.page.currentPage,
                pagesize: this.$refs.page.pageSize,
            };
            console.log(where);
            axios.post("/book/getBooksByWhere", where).then((res) => {
                console.log(res.data);
                if (res.data.code == 200) {
                    this.booklist = res.data.result.list;
                    this.total = res.data.result.total;
                }
            });
        },

        handleDelete() {
            ElMessageBox.confirm("你确定删除?", "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "警告",
            })
                .then(() => {

                    axios.post("/book/deleteUsersByIds",  this.multipleSelection).then((res) => {
                        console.log(">>>>>" + res.data.code);
                        if (res.data.code == 200) {
                            this.getBooklist();
                            ElMessage({
                                type: "success",
                                message: res.data.msg,
                            });
                        }else if(res.data.code==-3)
                        {
                            ElMessage({
                                type: "error",
                                message: res.data.msg,
                            });
                        }else{
                            ElMessage({
                                type: "error",
                                message: res.data.msg,
                            });
                        }
                    });
                })
                .catch(() => {
                    ElMessage({
                        type: "info",
                        message: "Delete canceled",
                    });
                });
        },

        addhandler() {
            this.option = "添加记录";
            this.dialogVisible = true;
            this.book = {};

        },
        Edithandler(index, row) {
            this.option = "修改记录";
            this.dialogVisible = true;
            this.book = row;
            //清空缓存中图片
            this.$refs.upload.clearFiles()
            //把旧图片显示注意$el.style.display = 'block'
            this.$refs.avatarImg.$el.style.display = 'block'


        },
        lendBook(index, row) {
            console.log(index, row);
            this.lendForm = row;
            this.lendForm.uid = this.loginUser.uid;
            if (this.lendForm.plus < 1) {
                ElMessage({
                    showClose: true,
                    type: "error",
                    message: "该书已经没有库存了",
                });
            } else {
                this.dialogLendVisible = true;
            }

            console.log("lendBook");
        },

        borrowBook() {
            axios
                .post("/book/borrowBook", this.lendForm, {
                    "Content-Type": "multipart/form-data",
                })
                .then((res) => {
                    console.log(res.data.code);
                    if (res.data.code == 200) {
                        this.dialogLendVisible = false;
                        ElMessage({
                            type: "success",
                            message: res.data.msg,
                        });
                        this.getBooklist();
                    } else {
                        this.dialogLendVisible = false;
                        ElMessage({
                            showClose: true,
                            type: "error",
                            message: res.data.msg,
                        });
                    }
                });
        },

        optionBook(option) {
            if (option == "添加记录") {
                axios.post("/book/addBookItem", this.book).then((res) => {
                    if (res.data.code == 200) {
                        // if (res.data.result > 0) {
                            this.submitUpload(res.data.result)
                        // }else{
                          this.getBooklist();
                        // }
                       
                        this.dialogVisible = false;
                        ElMessage({
                            type: "success",
                            message: res.data.msg,
                        });
                    } else {
                        ElMessage({
                            showClose: true,
                            type: "error",
                            message: res.data.msg,
                        });
                    }
                });
            } else {
                axios.post("/book/updateBookByID", this.book).then((res) => {
                    if (res.data.code == 200) {
                        ElMessage({
                            type: "success",
                            message: res.data.msg,
                        });
                        this.submitUpload(res.data.result)
                        //   this.getBooklist();
                        this.dialogVisible = false;
                    } else {
                        ElMessage({
                            showClose: true,
                            type: "error",
                            message: res.data.msg,
                        });
                    }
                });
            }
        },
    },
};
</script>
<style>
.el-table .warning-row {
    --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.el-table .success-row {
    --el-table-tr-bg-color: var(--el-color-success-light-9);
}

.example-pagination-block+.example-pagination-block {
    margin-top: 10px;
}

.example-pagination-block .example-demonstration {
    margin-bottom: 16px;
}
</style>
